#include "geometry.h"

/*
	Check if p1, p2, p3 are counter-clockwise
	RETURN:
		1: counter-clockwise
		0: clockwise
*/
char counterClockwise(const Point2D *p1, const Point2D *p2, const Point2D *p3)
{
	/* dx1 * dy2 - dy1 * dx2 */
	double ccw = (p2->x - p1->x) * (p3->y - p1->y) - (p2->y - p1->y)*(p3->x - p1->x);
	return (ccw > 0)?1:0;
}

double left(vector<Point2D*> points)
{
	double min = points[0]->x;
	int i, count = points.size();

	for(i=1; i<count; i++)
	{
		if(points[i]->x < min)
			min = points[i]->x;
	}

	return min;
}

double top(vector<Point2D*> points)
{
	double max = points[0]->y;
	int i, count = points.size();

	for(i=1; i<count; i++)
	{
		if(points[i]->y > max)
			max = points[i]->y;
	}

	return max;
}

double right(vector<Point2D*> points)
{
	double max = points[0]->x;
	int i, count = points.size();

	for(i=1; i<count; i++)
	{
		if(points[i]->x > max)
			max = points[i]->x;
	}

	return max;
}

double bottom(vector<Point2D*> points)
{
	double min = points[0]->y;
	int i, count = points.size();

	for(i=1; i<count; i++)
	{
		if(points[i]->y < min)
			min = points[i]->y;
	}

	return min;
}

/*
	This function finds intersection of AB and CD
*/
Point2D* intersection2D(Point2D A, Point2D B, Point2D C, Point2D D)
{
	double a1, b1, a2, b2, x, y;

	//Line AB: y = a1x + b1
	a1 = (B.y - A.y)/(B.x - A.x);
	b1 = A.y - a1*A.x;

	//Line CD: y = a2x + b2
	a2 = (D.y - C.y)/(D.x - C.x);
	b2 = C.y - a2*C.x;

	if(a1 == a2)
		return NULL;

	x = (b2 - b1)/(a1 - a2);
	y = a1*x + b1;

	Point2D *p = new Point2D;
	p->x = x;
	p->y = y;

	return p;
}